package com.supervision.manage.service

import com.fly.base.core.Core
import com.fly.base.exception.ExistsException
import com.fly.base.exception.NotExistsException
import com.fly.base.misc.pagination.Pagination
import com.fly.base.util.DateFormatUtil
import com.fly.base.util.PasswordHash
import com.supervision.domain.bean.po.AdminSearchPO
import com.supervision.domain.enums.AdminEnum
import com.supervision.domain.enums.TokenEnum
import com.supervision.domain.exception.NotAllowedException
import com.supervision.domain.model.Admin
import com.supervision.manage.mapper.AdminMapper
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class AdminService {

    @Autowired
    lateinit var tokenService: TokenService

    @Autowired
    lateinit var adminMapper: AdminMapper

    fun login(username: String, password: String): MutableMap<String, Any>? {
        val admin = Core.Q().queryOne(Admin::class.java, """
            select * from admin where weight >= 0 and username = ? limit 1
        """.trimIndent(), username)
                ?: throw NotExistsException("管理员不存在")

        if (!PasswordHash.validatePassword(password, admin.password)) {
            throw NotAllowedException("密码错误")
        }

        admin.lastLoginTime = DateFormatUtil.time()
        admin.save()

        val token = tokenService.create(TokenEnum.TYPE_SYSTEM.code, admin.id, admin.type, 1, 0)

        return hashMapOf(
                "token" to token.token,
                "admin" to admin.process(arrayOf("id", "type", "username", "name", "last_login_time", "create_time"))
        )
    }

    fun addAdmin(username: String, password: String, name: String) {
        val admin = Core.Q().findByCol(Admin::class.java, "username", username)
        if (admin != null && admin.weight >= 0) {
            throw ExistsException("用户名已被使用")
        }
        val data = Admin()
        data.type = AdminEnum.TYPE_AUDITOR.code
        data.username = username
        data.name = name
        data.password = PasswordHash.createHash(password)
        data.save()
    }

    fun updateAdmin(id: Long, username: String, name: String) {
        if (id == 1L) {
            throw NotAllowedException("超级管理员不能操作")
        }
        var admin = Core.Q().findByCol(Admin::class.java, "username", username)
        if (admin != null && admin.weight >= 0 && admin.id != id) {
            throw ExistsException("用户名已被使用")
        }

        admin = Admin.findOrFail(id)
        admin.type = AdminEnum.TYPE_AUDITOR.code
        admin.username = username
        admin.name = name
        admin.save()
    }

    fun deleteAdmin(id: Long) {
        if (id == 1L) {
            throw NotAllowedException("超级管理员不能操作")
        }
        val admin = Admin.findOrFail(id)
        admin.delete()
    }

    fun getAdminList(po: AdminSearchPO): HashMap<String, Any> {
        val adminList = adminMapper.getAdminList(po, Pagination.limitSql(po.page))
        val count = adminMapper.countAdminList(po, "")

        return hashMapOf(
                "list" to adminList,
                "count" to count
        )
    }

    fun resetPassword(id: Long, password: String) {
        val admin = Admin.findOrFail(id)
        admin.password = PasswordHash.createHash(password)
        admin.save()
    }

    fun updatePassword(userId: Long, oldPwd: String, newPwd: String) {
        val admin = Admin.findOrFail(userId)
        if (!PasswordHash.validatePassword(oldPwd, admin.password)) {
            throw NotAllowedException("旧密码错误")
        }

        admin.password = PasswordHash.createHash(newPwd)
        admin.save()
    }

    fun getInfo(userId: Long): HashMap<String, Any?> {
        val admin = Admin.findById(userId)
        return hashMapOf<String, Any?>(
                "admin" to admin
        )
    }
}